package com.lean.android.ad

import android.app.Activity
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.lean.android.ad.core.Ad
import com.lean.android.ad.core.AdLoadState
import com.lean.android.ad.core.AdLoaders

class FeedAdProvider {

    var feedAdState: FeedAdState by mutableStateOf(FeedAdState.Loading)

    suspend fun requestFeedAd(activity: Activity) {
        val tempState = feedAdState
        val requireLoad = tempState is FeedAdState.Loading || tempState is FeedAdState.Error //需要重新加载
        if(requireLoad) {
            feedAdState = when (val adLoadState = AdLoaders.loadFeedAd(activity)) {
                is AdLoadState.Success -> {
                    FeedAdState.Loaded(ad = adLoadState.ad)
                }

                is AdLoadState.Error -> {
                    FeedAdState.Error(
                        code = adLoadState.code, message = adLoadState.message
                    )
                }
            }
        }
    }

    fun cachedFeedAd() {
        val tempState = feedAdState
        if (tempState is FeedAdState.Loaded) {
            feedAdState = FeedAdState.Cached(tempState.ad)
        }
    }

    fun closeFeedAd(){
        feedAdState = FeedAdState.Closed
    }

}


sealed interface FeedAdState {
    data object Loading : FeedAdState
    data object Closed : FeedAdState
    data class Cached(val ad: Ad) : FeedAdState
    data class Error(val code: Int, val message: String?) : FeedAdState
    data class Loaded(val ad: Ad) : FeedAdState
}